<template>
  <Head :title="title" />
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-40">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between items-center h-16">
          <!-- Logo 和标题 -->
          <div class="flex items-center space-x-4">
            <Link :href="route('admin.dashboard')" class="flex items-center space-x-3 hover:opacity-80 transition-opacity">
              <div class="w-8 h-8 bg-gray-900 rounded-lg flex items-center justify-center">
                <img 
                  :src="appConfig.logo" 
                  :alt="appConfig.name"
                  class="w-5 h-5 text-white"
                  @error="handleLogoError"
                />
              </div>
              <h1 class="text-xl font-semibold text-gray-900">{{ appConfig.name }}</h1>
            </Link>
          </div>

          <!-- 导航菜单 -->
          <nav class="hidden lg:flex space-x-1">
            <template v-for="item in navigation" :key="item.name">
              <!-- 有子菜单的导航项 -->
              <div v-if="item.children" class="relative" v-click-outside="() => openDropdown === item.name ? openDropdown = null : null">
                <button
                  @click="openDropdown = openDropdown === item.name ? null : item.name"
                  :class="[
                    isCurrentPageInGroup(item.children)
                      ? 'text-gray-900 bg-gray-100' 
                      : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50', 
                    'px-3 py-2 text-sm font-medium rounded-md transition-all duration-200 flex items-center space-x-2'
                  ]">
                  <component :is="item.icon" class="h-4 w-4" aria-hidden="true" />
                  <span>{{ item.name }}</span>
                  <ChevronDownIcon :class="[openDropdown === item.name ? 'rotate-180' : '', 'h-3 w-3 transition-transform']" />
                </button>
                
                <!-- 下拉菜单 -->
                <TransitionRoot as="template" :show="openDropdown === item.name">
                  <TransitionChild 
                    as="template" 
                    enter="transition ease-out duration-100" 
                    enter-from="transform opacity-0 scale-95" 
                    enter-to="transform opacity-100 scale-100" 
                    leave="transition ease-in duration-75" 
                    leave-from="transform opacity-100 scale-100" 
                    leave-to="transform opacity-0 scale-95">
                    <div class="absolute left-0 z-10 mt-2 w-48 origin-top-left rounded-md bg-white py-1 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
                      <Link
                        v-for="child in item.children"
                        :key="child.href"
                        :href="child.href"
                        @click="openDropdown = null"
                        :class="[
                          isCurrentPage(child)
                            ? 'bg-gray-100 text-gray-900'
                            : 'text-gray-700 hover:bg-gray-50',
                          'block px-4 py-2 text-sm'
                        ]">
                        {{ child.name }}
                      </Link>
                    </div>
                  </TransitionChild>
                </TransitionRoot>
              </div>
              
              <!-- 普通导航项 -->
              <Link v-else :href="item.href" 
                    :class="[
                      isCurrentPage(item) 
                        ? 'text-gray-900 bg-gray-100' 
                        : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50', 
                      'px-3 py-2 text-sm font-medium rounded-md transition-all duration-200'
                    ]">
                <div class="flex items-center space-x-2">
                  <component :is="item.icon" class="h-4 w-4" aria-hidden="true" />
                  <span>{{ item.name }}</span>
                </div>
              </Link>
            </template>
          </nav>

          <!-- 移动端菜单按钮 -->
          <button @click="mobileMenuOpen = !mobileMenuOpen" 
                  class="lg:hidden p-2 rounded-md text-gray-600 hover:text-gray-900 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-gray-900 transition-colors">
            <span class="sr-only">打开主菜单</span>
            <Bars3Icon v-if="!mobileMenuOpen" class="h-6 w-6" aria-hidden="true" />
            <XMarkIcon v-else class="h-6 w-6" aria-hidden="true" />
          </button>

          <!-- 右侧操作区 -->
          <div class="flex items-center space-x-3">
            <!-- 前往商城 -->
            <Link :href="route('home')" 
                  class="hidden md:flex items-center space-x-1 px-3 py-1.5 text-sm text-gray-600 hover:text-gray-900 border border-gray-300 rounded-md hover:bg-gray-50 transition-all duration-200">
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
              </svg>
              <span>{{ appConfig.texts.goToShop }}</span>
            </Link>

            <!-- 用户菜单 -->
            <div class="relative" v-click-outside="closeUserMenu">
              <button @click="userMenuOpen = !userMenuOpen" 
                      class="flex items-center text-sm rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-all duration-200 hover:bg-gray-50 p-1.5">
                <span class="sr-only">打开用户菜单</span>
                <div class="h-8 w-8 rounded-full bg-gradient-to-br from-gray-700 to-gray-900 flex items-center justify-center">
                  <span class="text-sm font-medium text-white">{{ userInitial }}</span>
                </div>
                <div class="ml-2 hidden md:block text-left">
                  <p class="text-sm font-medium text-gray-900">{{ user?.name }}</p>
                  <p class="text-xs text-gray-500">{{ appConfig.texts.admin }}</p>
                </div>
                <ChevronDownIcon 
                  :class="[userMenuOpen ? 'rotate-180' : '', 'ml-1 h-4 w-4 text-gray-400 transition-transform duration-200']" 
                  aria-hidden="true" />
              </button>

              <!-- 用户下拉菜单 -->
              <TransitionRoot as="template" :show="userMenuOpen">
                <TransitionChild 
                  as="template" 
                  enter="transition ease-out duration-200" 
                  enter-from="transform opacity-0 scale-95" 
                  enter-to="transform opacity-100 scale-100" 
                  leave="transition ease-in duration-75" 
                  leave-from="transform opacity-100 scale-100" 
                  leave-to="transform opacity-0 scale-95">
                  <div class="origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 divide-y divide-gray-100">
                    <!-- 用户信息 -->
                    <div class="px-4 py-3">
                      <p class="text-sm font-medium text-gray-900">{{ user?.name }}</p>
                      <p class="text-sm text-gray-500 truncate">{{ user?.email || user?.phone || appConfig.texts.admin }}</p>
                    </div>
                    
                    <!-- 菜单选项 -->
                    <div class="py-1">
                      <Link :href="route('home')" 
                            @click="closeUserMenu"
                            class="group flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors duration-200">
                        <svg class="mr-3 h-4 w-4 text-gray-400 group-hover:text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
                        </svg>
                        {{ appConfig.texts.goToShopHome }}
                      </Link>
                      <Link :href="route('admin.system-settings')" 
                            @click="closeUserMenu"
                            class="group flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors duration-200">
                        <svg class="mr-3 h-4 w-4 text-gray-400 group-hover:text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        </svg>
                        {{ appConfig.texts.systemSettings }}
                      </Link>
                      <Link :href="route('admin.logs.index')" 
                            @click="closeUserMenu"
                            class="group flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors duration-200">
                        <svg class="mr-3 h-4 w-4 text-gray-400 group-hover:text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        </svg>
                        {{ appConfig.texts.operationLogs }}
                      </Link>
                    </div>

                    <!-- 退出登录 -->
                    <div class="py-1">
                      <Link :href="route('logout')" 
                            method="post" 
                            as="button"
                            @click="closeUserMenu"
                            class="group flex items-center w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors duration-200">
                        <svg class="mr-3 h-4 w-4 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                        </svg>
                        {{ appConfig.texts.logout }}
                      </Link>
                    </div>
                  </div>
                </TransitionChild>
              </TransitionRoot>
            </div>
          </div>
        </div>
      </div>

      <!-- 移动端导航菜单 -->
      <TransitionRoot as="template" :show="mobileMenuOpen">
        <TransitionChild 
          as="template" 
          enter="transition ease-out duration-200" 
          enter-from="transform opacity-0 -translate-y-1" 
          enter-to="transform opacity-100 translate-y-0" 
          leave="transition ease-in duration-150" 
          leave-from="transform opacity-100 translate-y-0" 
          leave-to="transform opacity-0 -translate-y-1">
          <div class="lg:hidden border-t border-gray-200 bg-white shadow-lg">
            <div class="px-2 pt-2 pb-3 space-y-1">
              <template v-for="item in navigation" :key="item.name">
                <!-- 有子菜单的移动端导航项 -->
                <div v-if="item.children">
                  <div class="px-3 py-2 text-xs font-semibold text-gray-500 uppercase tracking-wider">
                    <div class="flex items-center space-x-2">
                      <component :is="item.icon" class="h-4 w-4" aria-hidden="true" />
                      <span>{{ item.name }}</span>
                    </div>
                  </div>
                  <Link
                    v-for="child in item.children"
                    :key="child.href"
                    :href="child.href"
                    @click="mobileMenuOpen = false"
                    :class="[
                      isCurrentPage(child)
                        ? 'bg-gray-100 text-gray-900'
                        : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900',
                      'block pl-8 pr-3 py-2 text-base font-medium rounded-md transition-colors duration-200'
                    ]">
                    {{ child.name }}
                  </Link>
                </div>
                
                <!-- 普通移动端导航项 -->
                <Link v-else :href="item.href" 
                      @click="mobileMenuOpen = false"
                      :class="[
                        isCurrentPage(item) 
                          ? 'bg-gray-100 text-gray-900' 
                          : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900', 
                        'block px-3 py-2 text-base font-medium rounded-md transition-colors duration-200'
                      ]">
                  <div class="flex items-center space-x-2">
                    <component :is="item.icon" class="h-5 w-5" aria-hidden="true" />
                    <span>{{ item.name }}</span>
                  </div>
                </Link>
              </template>
            </div>
          </div>
        </TransitionChild>
      </TransitionRoot>
    </header>

    <!-- 主内容区域 -->
    <main class="flex-1">
      <div class="py-8">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <!-- 页面标题 -->
          <div class="mb-8">
            <div class="md:flex md:items-center md:justify-between">
              <div class="min-w-0 flex-1">
                <h2 class="text-2xl font-light leading-7 text-gray-900 sm:truncate sm:text-3xl sm:tracking-tight">
                  {{ title }}
                </h2>
                <p class="mt-1 text-sm text-gray-600">
                  {{ subtitle }}
                </p>
              </div>
              <div class="mt-4 flex md:ml-4 md:mt-0">
                <slot name="actions" />
              </div>
            </div>
          </div>

          <!-- 页面内容 -->
          <slot />
        </div>
      </div>
          </main>
        </div>
        
        <!-- 通知容器 -->
        <NotificationContainer />
      </template>

<script setup>
import { ref, watch, computed } from 'vue'
import { Link, Head, usePage } from '@inertiajs/vue3'
import { TransitionChild, TransitionRoot } from '@headlessui/vue'
import {
  HomeIcon,
  ListBulletIcon,
  UserCircleIcon,
  ClockIcon,
  ChevronDownIcon,
  Cog6ToothIcon,
  Bars3Icon,
  XMarkIcon,
  ClipboardDocumentListIcon,
} from '@heroicons/vue/24/outline'
import NotificationContainer from '@/Components/NotificationContainer.vue'
import { useNotification } from '@/composables/useNotification'

// 定义 props
const props = defineProps({
  title: {
    type: String,
    default: '管理后台'
  },
  subtitle: {
    type: String,
    default: '管理系统概览'
  }
})

// Flash 消息处理
const page = usePage()
const { showSuccess, showError, showInfo } = useNotification()

// 获取当前用户信息
const user = computed(() => page.props.auth?.user)

// 应用配置
const appConfig = computed(() => {
  return {
    name: page.props.systemSettings?.site_name || 'Orange Tech',
    logo: page.props.systemSettings?.site_logo || '/images/logo.svg',
    texts: {
      goToShop: '前往商城',
      goToShopHome: '前往商城首页',
      admin: '管理员',
      systemSettings: '系统配置',
      operationLogs: '操作日志',
      logout: '退出登录'
    }
  }
})

// 用户名首字母
const userInitial = computed(() => {
  return user.value?.name?.charAt(0).toUpperCase() || 'A'
})

// Logo 错误处理
const handleLogoError = (event) => {
  // 如果 logo 加载失败，回退到默认的 SVG 图标
  const target = event.target
  target.style.display = 'none'
  
  // 创建默认 SVG 图标
  const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
  svg.setAttribute('class', 'w-5 h-5 text-white')
  svg.setAttribute('fill', 'none')
  svg.setAttribute('stroke', 'currentColor')
  svg.setAttribute('viewBox', '0 0 24 24')
  
  const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
  path.setAttribute('stroke-linecap', 'round')
  path.setAttribute('stroke-linejoin', 'round')
  path.setAttribute('stroke-width', '2')
  path.setAttribute('d', 'M13 10V3L4 14h7v7l9-11h-7z')
  
  svg.appendChild(path)
  target.parentNode.appendChild(svg)
}

// 监听 flash 消息
watch(() => page.props.flash, (flash) => {
  if (flash?.success) {
    showSuccess('操作成功', flash.success)
  }
  if (flash?.error) {
    showError('操作失败', flash.error)
  }
  if (flash?.info) {
    showInfo('提示信息', flash.info)
  }
}, { immediate: true, deep: true })

// 用户菜单状态
const userMenuOpen = ref(false)

// 关闭用户菜单
const closeUserMenu = () => {
  userMenuOpen.value = false
}

// 移动端菜单状态
const mobileMenuOpen = ref(false)

// 导航菜单
const navigation = [
  { name: '仪表板', href: route('admin.dashboard'), icon: HomeIcon },
  { 
    name: '商品管理', 
    icon: ListBulletIcon,
    children: [
      { name: '产品管理', href: route('admin.products.index') },
      { name: '分类管理', href: route('admin.categories.index') },
      { name: '规格模板', href: route('admin.specification-templates.index') },
    ]
  },
  { 
    name: '订单管理', 
    icon: ClockIcon,
    children: [
      { name: '订单列表', href: route('admin.orders.index') },
      { name: '售后管理', href: route('admin.after-sales.index') },
    ]
  },
  { 
    name: '营销管理', 
    icon: ClipboardDocumentListIcon,
    children: [
      { name: '优惠券管理', href: route('admin.coupons.index') },
    ]
  },
  { 
    name: '用户管理', 
    icon: UserCircleIcon,
    children: [
      { name: '用户列表', href: route('admin.users.index') },
    ]
  },
  { 
    name: '系统设置', 
    icon: Cog6ToothIcon,
    children: [
      { name: '系统配置', href: route('admin.system-settings') },
      { name: '队列管理', href: route('admin.queue.index') },
      { name: '发送消息', href: route('admin.notifications.send') },
      { name: '操作日志', href: route('admin.logs.index') },
    ]
  },
]

// 下拉菜单状态
const openDropdown = ref(null)

// 判断当前页面 - 使用 Inertia.js 最佳实践
const isCurrentPage = (item) => {
  const currentUrl = page.url
  const hrefPath = item.href?.replace(/^https?:\/\/[^\/]+/, '')
  
  // 精确匹配
  if (currentUrl === hrefPath) return true
  
  // 匹配子路径（例如 /admin/products/1 匹配 /admin/products）
  // 排除仪表板，因为仪表板应该精确匹配
  const dashboardPath = route('admin.dashboard').replace(/^https?:\/\/[^\/]+/, '')
  if (hrefPath !== dashboardPath && currentUrl.startsWith(hrefPath)) return true
  
  return false
}

// 判断当前页面是否在分组内
const isCurrentPageInGroup = (children) => {
  return children.some(child => isCurrentPage(child))
}

// Click outside directive
const vClickOutside = {
  mounted(el, binding) {
    el.clickOutsideEvent = (event) => {
      if (!(el === event.target || el.contains(event.target))) {
        binding.value()
      }
    }
    document.addEventListener('click', el.clickOutsideEvent)
  },
  unmounted(el) {
    document.removeEventListener('click', el.clickOutsideEvent)
  }
}
</script>